package com.msb.dongbao.common.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author: mayu
 * @date: 2021年05月27日 11:34
 */
public class JwtUtil {
    private static final String secret = "sdfsfdqw";

    public static String createToken(String subject) {
        String token = Jwts.builder()
                .setSubject(subject)
                //设置token有效期为60秒
                .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60))
                .signWith(SignatureAlgorithm.HS256, secret)
                .compact();
        return token;
    }

    public static String parseToken(String token) {
        Claims claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
        String subject = claims.getSubject();
        return subject;
    }

    public static void main(String[] args) throws InterruptedException {
        String subject = "教育";
        String token = createToken(subject);
        System.out.println("token：" + token);

        String s = parseToken(token);
        System.out.println("解析出来的token为：" + s);

        TimeUnit.SECONDS.sleep(10);

        s = parseToken(token);
        System.out.println("解析出来的token为：" + s);
    }
}
